package com.sjlh.centurylianhua.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sjlh.centurylianhua.dto.SearchCon;
import com.sjlh.centurylianhua.entity.*;
import com.sjlh.centurylianhua.mapper.InventoryMapper;
import com.sjlh.centurylianhua.mapper.PurchaseLogInfoMapper;
import com.sjlh.centurylianhua.mapper.PurchaseLogMapper;
import com.sjlh.centurylianhua.utils.ResultData;
import com.sjlh.centurylianhua.utils.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.*;

@CrossOrigin
@RestController
@RequestMapping("/purchase")
public class PurchaseController {

    @Resource
    private PurchaseLogMapper purchaseMapper;
    @Resource
    private InventoryMapper inventoryMapper;
    @Resource
    private PurchaseLogInfoMapper purchaseLogInfo;
    /**
     * 添加进货日志
     * */
    @RequestMapping("/add")
    public Object add(@RequestBody PurchaseLog purchaseLog) {
        //自动生存订单号
        purchaseLog.setCodeId("SJLH"+ new Date().getTime());
        long r=purchaseMapper.insert(purchaseLog);
        //存储id返回给前端方便添加进货日志详情
        long id=purchaseLog.getId();
        if (r==1)
            return new ResultData(true,20000,"添加成功",true,id);
        else
            return new ResultData(false,20001,"添加失败",false,null);

    }
    /**
     * 查询所有进货日志
     * */
    @RequestMapping("/getAll")
    public Object getAll(@RequestBody SearchCon searchCon){
        QueryWrapper<PurchaseLog> wrapper = new QueryWrapper<>();
        //当条件不为空时，添加where条件
        wrapper.eq(searchCon.getTypeName()!=null,"supplierId",searchCon.getTypeName());
        wrapper.eq(searchCon.getTypeName2()!=null,"depotId",searchCon.getTypeName2());
        wrapper.eq(searchCon.getTypeName3()!=null,"state",searchCon.getTypeName3());
        wrapper.ge(StringUtils.isnotNullObj(searchCon.getBeginDate()),"creatTime",searchCon.getBeginDate());
        wrapper.le(StringUtils.isnotNullObj(searchCon.getEndDate()),"creatTime",searchCon.getEndDate());
        //追加多表连接的sql语句
        wrapper.apply("depot.id = purchase_log.depotId and purchase_log.supplierId = supplier.id and purchase_log.userId=user.id");
        //没有分页时查询所有模块
        if(searchCon.getPage()==null){
            List<PurchaseLog> list = purchaseMapper.getInfo(wrapper);
            long count = purchaseMapper.getInfo(wrapper).size();
            ResultData rs=new ResultData(true,20000,"成功",list,count);
            return rs;
        }else {
            // 封装分页对象
            Page<PurchaseLog> page = new Page<PurchaseLog>(searchCon.getPage(), searchCon.getLimit());
            Page<PurchaseLog> depotPage = purchaseMapper.getInfoPage(page, wrapper);
            List<PurchaseLog> list=depotPage.getRecords();//所有数据
            long count=depotPage.getTotal();//总条数
            ResultData rs=new ResultData(true,20000,"成功",list,count);
            return rs;
        }
    }

    /**
     * 根据供货商查询进货日志
     * */
    @RequestMapping("/getBySupplier")
    public Object getBySupplier(@RequestBody SearchCon searchCon){
        QueryWrapper<PurchaseLog> wrapper = new QueryWrapper<>();
        wrapper.eq("supplierId",searchCon.getTypeName());
        List<PurchaseLog> list = purchaseMapper.getInfo(wrapper);
        long count = purchaseMapper.selectList(wrapper).size();
        ResultData rs=new ResultData(true,20000,"成功",list,count);
        return rs;
    }

    /**
     * 修改进货日志状态并在入库时修改库存
     * */
    @RequestMapping("/set")
    public Object setRemark(@RequestBody PurchaseLog purchaseLog) {
        UpdateWrapper<PurchaseLog> wrapper = new UpdateWrapper<>();
        wrapper.set("state", purchaseLog.getState());
        wrapper.eq("id",purchaseLog.getId());
        long r=purchaseMapper.update(null,wrapper);
        if (r==1){
            //判断是否入库操作
            if (purchaseLog.getState()==2){
                //在修改成功后执行修改库存操作
                QueryWrapper<PurchaseLogInfo> selectPurchase = new QueryWrapper<>();
                selectPurchase.eq("purchaseId",purchaseLog.getId());
                //查询详情表中的商品和进货的数量
                List<PurchaseLogInfo> list = purchaseLogInfo.selectList(selectPurchase);
                for (PurchaseLogInfo purchase:list) {
                    //查询库存表中是否有进货商品库存
                    QueryWrapper<Inventory> selectInventory = new QueryWrapper<>();
                    selectInventory.eq("productId", purchase.getProductId());
                    selectInventory.eq("depotId",purchaseLog.getDepotId());
                    Inventory inventory = inventoryMapper.selectOne(selectInventory);
                    //没有时添加
                    if (inventory==null){
                        Inventory inventor = new Inventory(purchase.getProductId(),purchaseLog.getDepotId(),Integer.parseInt(purchase.getStandby2()));
                        inventoryMapper.insert(inventor);
                    }else {
                        //有库存时修改库存
                        UpdateWrapper<Inventory> updateWrapper = new UpdateWrapper();
                        updateWrapper.setSql("depotNum = depotNum + " +purchase.getStandby2());//进货数量
                        updateWrapper.eq("productId",purchase.getProductId());//商品id
                        updateWrapper.eq("depotId",purchaseLog.getDepotId());//仓库id
                        inventoryMapper.update(null,updateWrapper);
                    }

                }
            }
            return new ResultData(true,20000,"修改成功",true,null);
        }else
            return new ResultData(false,20001,"修改失败",false,null);

    }
    //销售统计图
    @RequestMapping("/purCount")
    public Object saleCount(@RequestBody SearchCon searchCon){
        List<Object> obj=new ArrayList<Object>();
        List<String> name=new ArrayList<String>();
        List<Integer> intlist=new ArrayList<Integer>();
        QueryWrapper<PurchaseLog> wrapper = new QueryWrapper<PurchaseLog>();
        Map<String,Object> map=new HashMap<String,Object>();
        wrapper.apply("user.id=pu.userId");
        //时间查询
        wrapper.ge(StringUtils.isnotNullObj(searchCon.getBeginDate()),"pu.creatTime",searchCon.getBeginDate());
        wrapper.le(StringUtils.isnotNullObj(searchCon.getEndDate()),"pu.creatTime",searchCon.getEndDate());
        if(searchCon.getTypeName()!=null && searchCon.getTypeName()==1){
            wrapper.apply("year(pu.creatTime)= year(now())");
        }
        List<PurchaseLog> sale=purchaseMapper.purCount(wrapper);
        for(PurchaseLog sa:sale){
            name.add(sa.getUserName());
            intlist.add(Integer.valueOf(sa.getStandby3()));
        }
        map.put("x",name);
        map.put("y",intlist);
        return new ResultData(true,20000,"成功",map,0L);
    }
}
